package org.icress.fusion.shiro

import java.util.Date

import org.icress.fusion.admin.Profile
import org.icress.fusion.b2b.Department
import org.icress.fusion.admin.Group


import org.apache.shiro.crypto.hash.Sha512Hash

class User {
    String username
    String passwordHash
    Profile profile
    Department department
    Group group
    Date dateCreated
    Date lastUpdated
    
    static hasMany = [ roles: Role, permissions: String ]
	static belongsTo = [group : Group]
    
    static constraints = {
        username(nullable: false, blank: false, unique: true, minSize:5, maxSize:25)
        passwordHash(nullable: false, blank: false, minSize:5)
        profile(nullable:true)
        department(nullable:true)
        group(nullable:true)
    }
    
    String toString() {
        return "$username"
    }

    def beforeValidate(){
        if(this.passwordHash == null){
            this.passwordHash = new Sha512Hash('gh123098& -.').toHex()
        }
    }

    def beforeInsert(){
        //如果部门不为空，则将用户加用到部门组中
        if(this.department != null){//办事处或者商务部用户，给用户分配组
            def departmentName = Department.get(this.department.id).name
            def group = Group.findByName(departmentName)
            this.group = group
        }
    }
    
    static mapping = {
        table 'SHIRO_USER'
    }
}
